import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const routes = [
  {
    path: '/reg',
    name: 'reg',
    meta: {
      title: '注册'
    },
    component: () => import('@/views/register')
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '登录'
    },
    component: () => import('@/views/login')
  },
  {
    path: '/',
    name: 'index',
    redirect: '/home',
    meta: {
      title: '大事件主页'
    },
    component: () => import('@/views/layout'),
    children: [
      {
        path: 'home',
        name: 'home',
        meta: {
          title: '首页'
        },
        component: () => import('@/views/home')
      },
      {
        path: 'user-info',
        name: 'user-info',
        meta: {
          title: '基本资料'
        },
        component: () => import('@/views/user/UserInfo')
      },
      {
        path: 'user-avatar',
        name: 'user-avatar',
        meta: {
          title: '更换头像'
        },
        component: () => import('@/views/user/UserAvatar')
      },
      {
        path: 'user-pwd',
        name: 'user-pwd',
        meta: {
          title: '重置密码'
        },
        component: () => import('@/views/user/UserPwd')
      },
      {
        path: 'art-cate',
        name: 'art-cate',
        meta: {
          title: '文章分类'
        },
        component: () => import('@/views/article/ArtCate')
      },
      {
        path: 'art-list',
        name: 'art-list',
        meta: {
          title: '文章列表'
        },
        component: () => import('@/views/article/ArtList')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

// 请求白名单
const whitePath = ['/reg', '/login']
// 前置路由守卫
// 有token则登录,没有则未登录
router.beforeEach((to, from, next) => {
  // 退出时清空token,不走这逻辑代码
  const token = store.state.token
  // 当token不为空并且username为空,则初始化数据
  if (token) {
    if (!store.state.userInfo.username) {
      store.dispatch('initUserInfo')
    }
    next()
  } else {
    // 在白名单则放行
    if (whitePath.includes(to.path)) {
      // 放行
      next()
    } else {
      Message.warning('请您先登录!')
      next('/login')
    }
  }
})

// 后置路由守卫
router.afterEach((to, from) => {
  document.title = to.meta.title
})

export default router
